<template>
  <view>
    <nav-bar :pageTitle="lang.page_name"/>
    <view style="overflow:hidden;margin:0 30rpx 0 30rpx;" :class="locale">
      <view class="upload-box">

        <!-- 照片选自框大 box-->
        <view class="flex-column gap-30">
          <view class="column-center gap-20">
            <view class="upload-card-box">
              <view v-if="idFront === ''" hover-class="hover" @click="showUploadImage(0)">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="44px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="uploaded-image" src="/static/print_id/id.png"/>
              </view>

              <template v-else>
                <view class="close-icon-box" @click="closeId(0)">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <view @click="onEditImage(0)">
                  <image class="uploaded-image" :src="idFront"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.id_front }}</view>
          </view>


          <view class="column-center gap-20">
            <view class="upload-card-box">
              <!-- 上传照片前-->
              <view v-if="idAfter===''" @click="showUploadImage(1)" hover-class="hover">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="44px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="uploaded-image" src="/static/print_id/id_sel.png"/>
              </view>

              <!-- 上传照片后-->
              <template v-else>
                <view class="close-icon-box" @click="closeId(1)">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <view @click="onEditImage(1)">
                  <image class="uploaded-image" :src="idAfter"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.id_after }}</view>
          </view>
        </view>
      </view>

      <!-- 打印-->
      <view style="margin-top: 30rpx;">
        <u-button
            :disabled="!idFront && !idAfter" shape="circle" @click="drawAndShareImage" size="large" color="#1073FF"
            :customStyle="{fontSize: '32rpx' }">
          {{ otherLang.print }}
        </u-button>
      </view>


      <!-- 给服务器发送的和打印出的-->
      <view class="canvas">
        <canvas style="width: 1588px; height: 2246px; " canvas-id="idCanvas" id="idCanvas"/>
      </view>

      <!--    上传中弹窗-->
      <my_upload_card :upload-name="lang.id_upload" :show="showUpload" :upload-progress="uploadProgress"/>

      <!-- 选择弹窗-->
      <upload-select-popup
          :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
          @close-popup="showUploadPopup = false"/>
    </view>
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/nav-bar.vue";
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import my_upload_card from "@/components/my_upload_card/index.vue";
import {editImageChange} from "@/utils/utils";
import {uploadImageServer} from "@/services/office";

export default {
  components: {my_upload_card, navBar, uploadSelectPopup},
  data() {
    return {
      idFront: '',
      idAfter: '',
      clickType: 0,
      showUpload: false, // 文件上传
      uploadProgress: 0, /// 进度调
      showUploadPopup: false,
    };
  },
  computed: {
    lang() {
      return this.$t('print_id')
    }
  },
  methods: {
    // 选择 正面上传还是背面上传
    showUploadImage(type) {
      this.clickType = type;
      this.showUploadPopup = true;
    },

    // 微信选取图片
    chooseMessage() {
      const that = this;
      uni.chooseMessageFile({
        count: 1,
        type: 'image',
        success(res) {
          that.processImage(res.tempFiles[0].path);
        }
      });
    },

    // 本地图片上传或拍照
    chooseImage(index) {
      const that = this;
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'],
        success: function (res) {
          that.processImage(res.tempFiles[0].tempFilePath);
        }
      });
    },

    // 处理图片编译
    async processImage(src) {
      try {
        const tempFilePath = await editImageChange(src);
        if (this.clickType === 0) {
          this.idFront = tempFilePath;
        } else {
          this.idAfter = tempFilePath;
        }
      } catch (error) {
        console.error('图片处理失败:', error);
      }
    },

    // 删除照片
    closeId(type) {
      if (type === 0) {
        this.idFront = ''
      } else {
        this.idAfter = ''
      }
    },

    // 编译照片
    onEditImage(type) {
      this.clickType = type;
      const url = type === 0 ? this.idFront : this.idAfter;
      this.processImage(url)
    },

    // 合成图片
    drawAndShareImage() {
      // 绘制背景海报到canvas
      // 长度85.6mm，宽度54mm // 身份证宽高 * 8
      const posterWidth = 684;      // 身份证宽度
      const posterHeight = 432;     // 身份证高度
      const a4Width = 1588;         // A4纸宽度
      const a4Height = 2246;        // A4纸高度

      const that = this;

      // 检查是否已上传照片
      if (!that.idFront && !that.idAfter) {
        uni.showToast({title: "请先上传图片", icon: 'none'});
        return;
      }

      uni.showLoading({title: '加载中....', mask: true})

      // 微信小程序特有代码
      const context = uni.createCanvasContext('idCanvas', this);

      context.fillStyle = "#FFFFFF";
      context.fillRect(0, 0, a4Width, a4Height);

      context.drawImage(that.idFront, (a4Width - posterWidth) / 2, a4Height / 2 - 220 - posterHeight, posterWidth, posterHeight);
      context.drawImage(that.idAfter, (a4Width - posterWidth) / 2, a4Height / 2, posterWidth, posterHeight);
      context.draw();

      setTimeout(() => {
        uni.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: a4Width,
          height: a4Height,
          destWidth: a4Width,
          destHeight: a4Height,
          canvasId: 'idCanvas',
          success(res) {
            // uni.saveImageToPhotosAlbum({
            //   filePath: tempFilePath,
            //   success() {
            //     tips.toast('保存成功')
            //   },
            // })
            console.log("driveCanvas -=-=", res);
            // 上传图片到服务器
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: res.tempFilePath,
              success: (res) => {
                console.log("success: (res) => -=-=-", res)
                const {code, data: {url}} = JSON.parse(res.data);
                console.log("Upload success:", JSON.parse(res.data).data);
                if (code === 200) {
                  uni.navigateTo({url: `/pages/photo_pay/photo_pay?type=1&image=` + encodeURIComponent(JSON.stringify(url))})
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          }
        });
      }, 2000)
    },
  }
}
</script>

<style lang="scss">

</style>
